var Staff = {

    selected_row_id: null,
    objGrid: null,

    init: function () {
        var self = this;

        self.objGrid = $('#flex').flexigrid({
            url: $('#table-url').val(),
            reload_after_add: false,
            dataType: 'json',
            colModel: [
                {display: 'ID', name: 'id', width: 20, sortable: false, align: 'left', hide: true},
                {display: 'First Name', name: 'fname', width: 100, sortable: true, align: 'left', hide: false, editable: {form: 'text', validate: 'empty', defval: ''}},
                {display: 'Middle Name', name: 'mname', width: 100, sortable: true, align: 'left', hide: false, editable: {form: 'text', validate: 'empty', defval: ''}},
                {display: 'Last Name', name: 'lname', width: 100, sortable: true, align: 'left', hide: false, editable: {form: 'text', validate: 'empty', defval: ''}},
                {display: 'Username', name: 'username', width: 80, sortable: true, align: 'left', hide: false, editable: {form: 'text', validate: 'empty', defval: ''}},
                {display: 'Telephone', name: 'fon_number', width: 80, sortable: true, align: 'left', hide: false, editable: {form: 'text', validate: 'empty', defval: ''}},
                {display: 'Email', name: 'email', width: 100, sortable: true, align: 'left', hide: false, editable: {form: 'text', validate: 'empty', defval: ''}},
                {display: 'Group', name: 'group_id', width: 130, sortable: true, align: 'left', hide: false, editable: {form: 'select', validate: '', defval: '', options: groups}},
                {display: 'Branch', name: 'branch_id', width: 130, sortable: true, align: 'left', hide: false, editable: {form: 'select', validate: '', defval: '', options: branches}},
                {display: 'Department', name: 'department_id', width: 120, sortable: true, align: 'left', hide: false, editable: {form: 'select', validate: '', defval: '', options: departments}}

            ],
            formFields: [
                {type: 'buttom', name: 'New', bclass: 'add', onpress: self.handleGridEvent},
                {separator: true},
                {type: 'buttom', name: 'Save', bclass: 'save', onpress: self.handleGridEvent},
                {separator: true},
                {type: 'buttom', name: 'Edit', bclass: 'edit', onpress: self.handleGridEvent},
                {separator: true},
                {type: 'buttom', name: 'Cancel', bclass: 'cancel', onpress: self.handleGridEvent},
                {separator: true},
                {type: 'buttom', name: 'Disable', bclass: 'disable', onpress: self.handleGridEvent},
                {separator: true},
                {type: 'buttom', name: 'Enable', bclass: 'enable', onpress: self.handleGridEvent},
                {separator: true},
                {type: 'buttom', name: 'Reset Password', bclass: 'reload', onpress: self.handleGridEvent}
            ],
            searchitems: [
                {display: 'First Name', name: 'fname', isdefault: true},
                {display: 'Middle Name', name: 'mname'},
                {display: 'Last Name', name: 'lname'},
                {display: 'Username', name: 'username'},
                {display: 'Telephone', name: 'fon_number'},
                {display: 'Email', name: 'email'}
            ],
            checkboxSelection: true,
            editablegrid: {
                use: true,
                url: $('#table-editable-url').val()
            },
            columnControl: false,
            sortname: "id",
            sortorder: "desc",
            usepager: true,
            useRp: true,
            rp: 15,
            showTableToggleBtn: false,
            height: 300,
            subgrid: {
                use: true,
                url: $('#table-sub-load-url').val(),
                colModel: [
                    {display: 'Project', name: 'project_id', width: 200, align: 'center', editable: {form: 'select', validate: '', defval: '', options: projects}}
                ],
                editablegrid: {
                    use: true,
                    url: $('#table-sub-editable-url').val()
                },
                formFields: [
                    {type: 'buttom', name: 'New', bclass: 'new', onpress: self.handleSubGridEvent},
                    {separator: true},
                    {type: 'buttom', name: 'Edit', bclass: 'edit', onpress: self.handleSubGridEvent},
                    {separator: true},
                    {type: 'buttom', name: 'Save', bclass: 'save', onpress: self.handleSubGridEvent},
                    {separator: true},
                    {type: 'buttom', name: 'Cancel', bclass: 'print', onpress: self.handleSubGridEvent},
                    {separator: true},
                    {type: 'buttom', name: 'Delete', bclass: 'delete', onpress: self.handleSubGridEvent}
                ]
            }
        });

        $('#cancel-btn').click(function () {
            document.getElementById('user-form').reset();
            //$.validationEngine.closePrompt('.formError', true);
            $.colorbox.close();
        });

        $('#save-btn').click(function () {
            self.resetPass();
        });
    },

    handleGridEvent: function (com, grid, json) {
        if (com == 'New') {
            Staff.objGrid.flexBeginAdd();
        }
        else if (com == 'Edit') {
            if (FlexObject.rowSelectedCheck(Staff.objGrid, grid)) {
                var row = FlexObject.getSelectedRows(grid);
                Staff.objGrid.flexBeginEdit(row[0]);
            }
        }
        else if (com == 'Save') {
            Staff.objGrid.flexSaveChanges();
        }
        else if (com == 'Cancel') {
            Staff.objGrid.flexCancel();
        }
        else if (com == 'Disable') {
            if (FlexObject.rowSelectedCheck(Staff.objGrid, grid)) {
                var url = $('#table_delete_url').val();
                Staff.change_status(Staff.objGrid, url, grid, 'disable');
            }
        }
        else if (com == 'Enable') {
            if (FlexObject.rowSelectedCheck(Staff.objGrid, grid)) {
                var url = $('#table_delete_url').val();
                Staff.change_status(Staff.objGrid, url, grid, 'enable');
            }
        }
        else if (com == 'Reset Password') {
            if (FlexObject.rowSelectedCheck(Staff.objGrid, grid, 1)) {
                var row_ids = FlexObject.getSelectedRowIds(grid);
                $('#user-form-window #user-form #user_id').val(row_ids[0]);

                $.colorbox({
                    inline: true,
                    scrolling: false,
                    overlayClose: false,
                    escKey: false,
                    title: 'User Information',
                    href: "#user-form-window"
                });
            }
        }

    },

    /*Universal Delete for all Main record DataTable*/
    change_status: function (griObject, url, grid, type) {
        var self = this;
        var row_ids = FlexObject.getSelectedRowIds(grid);

        jConfirm('Are you sure you want to continue ?', 'Confirm', function (confirmation) {
            if (confirmation) {
                $.post(url, {'ids[]': row_ids, 'status': type}, function (response) {
                    //delete was successful, remove checkbox rows
                    if (response.code == 0) {
                        griObject.flexNotify('Disabled', response.msg, 'success');
                        if (typeof callback == 'function') {
                            callback();
                        }
                        self.objGrid.flexReload();
                    }
                    else if (response.code == 1) {
                        griObject.flexNotify('Disabled', response.msg, 'error');
                    }
                }, "json");
            }
        });
    },

    delete_: function (griObject, grid_dom, url, type) {
        var self = this;
        if (type == 'main') {
            Jlib.do_delete(griObject, url, grid_dom);
        }
        else {
            Jlib.do_sub_delete(griObject, url, grid_dom);
        }
    },


    resetPass: function () {
        var self = this;
        /* Validate the form*/
        // var validationStatus = $('#user-form').validationEngine({returnIsValid:true});
        /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
        //  if (validationStatus) {
        var query = $('#user-form').serialize();
        var url = $("#reset-pass-url").val();
        /* Send the data to the server and handle the server response */
        $.ajax({
            url: url,
            data: query,
            dataType: 'json',
            type: 'POST',
            success: function (response) {
                var txt = '';
                if (typeof response.msg == 'object') {
                    for (megTxt in response.msg) {
                        txt += response.msg[megTxt] + '<br />';
                    }
                }
                else {
                    txt = response.msg
                }
                //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*

                //jLib.message(txt, 'success');
                Jlib.message('Reset Password', txt, 'success');

                if (response.code === 0) {
                    document.getElementById('user-form').reset();
                    //$.validationEngine.closePrompt('.formError', true)
                    $.colorbox.close();
                }
                //* When there are Errors *//*
                else if (response.code === 1) {
                    Jlib.message('Reset Password', txt, 'error');
                }
            },
            error: function (xhr) {
                console.log(xhr.responseText);
                Jlib.serverError();
            }
        });
        // }
    },

    handleSubGridEvent: function (com, inner_table) {
        if (com == 'New') {
            Staff.objGrid.flexBeginSubAdd(inner_table);
        }
        else if (com == 'Edit') {
            var rows = FlexObject.getSelectedSubRows(inner_table);
            //we only need to edit the first one we can't do multiple editing
            if (rows.length > 0) {
                Staff.objGrid.flexBeginSubEdit(rows[0]);
            }
        }
        else if (com == 'Save') {
            Staff.objGrid.flexSubSaveChanges();
        }
        else if (com == 'Cancel') {
            Staff.objGrid.flexSubCancel();
        }
        else if (com == 'Delete') {
            if (FlexObject.rowSubSelectedCheck(Staff.objGrid, inner_table)) {
                var url = $('#table-sub_delete_url').val();
                Staff.delete_(Staff.objGrid, inner_table, url, 'sub');
            }
        }
    }
};

/* when the page is loaded */
$(document).ready(function () {
    Staff.init();
});